<?php
declare (strict_types=1);

namespace app\model\log;

use think\Model;
use crmeb\basic\BaseModel;
use crmeb\traits\ModelTrait;
use app\model\worker\RepairWorker;
use think\model\relation\BelongsTo;

/**
 * @property int $id
 * @property int $type 1是登录  2是退出登录
 * @property int $worker_id
 * @property string $created_at
 * @property string $device_type 设备类型;mobile,android,iphone,ipad,web,pc,mac,wxapp,ios
 * @property string $ip
 * @property-read \app\model\worker\RepairWorker $worker
 */
class WorkerLoginLog extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'worker_login_log';

    use ModelTrait;

    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created_at';
    protected $updateTime = false;

    /**
     * 用户id
     * @param Model $query
     * @param $value
     */
    public function searchWorkerIdAttr($query, $value)
    {
        if ($value) {
            $query->where('worker_id', 'in', $value);
        }
    }

    /**
     * 类型 1是登录 2是退出登录
     * @param Model $query
     * @param $value
     */
    public function searchTypeAttr($query, $value)
    {
        if ($value) {
            $query->where('type', $value);
        }
    }

    /**
     * 时间范围
     * @param Model $query
     * @param $value
     */
    public function searchDateAttr($query, $value)
    {
        if ($value) {
//            halt($value);
//            $query->where('created_at', '>=', $value[0] / 1000)->where('created_at', '<', ($value[1] / 1000) + 86400);
//            $query->whereBetween('created_at', [$value[0] / 1000, ($value[1] / 1000) + 86400]);
            $query->whereTime('created_at', '>=', date('Y-m-d H:i:s', $value[0] / 1000))
                ->whereTime('created_at', '<', date('Y-m-d H:i:s', ($value[1] / 1000) + 86400));
        }
    }

    /**
     * @return BelongsTo
     */
    public function worker(): BelongsTo
    {
        return $this->belongsTo(RepairWorker::class, 'worker_id', 'id');
    }
}
